<template>
    <div class="relative">
        <img src="http://or9v0p9za.bkt.clouddn.com/downloadPc.png" style="height: 100vh; width: 100vw" class="absolute pin-l pin-t">
        <div class="login-page">
            <el-card class="z-10 px-8">
                <div class="title mb-4">胶我选后台管理</div>
                <el-form :model="form" :rules="rules" ref="form" label-position="left" @keyup.enter.native="login" label-width="80px">
                    <template v-if="type == 1">
                        <el-form-item prop="username" label="手机号">
                            <el-input class="w-full" :autofocus="true" placeholder="请输入手机号" v-model="form.username"></el-input>
                        </el-form-item>
                        <el-form-item prop="password" label="密码">
                            <el-input class="w-full" placeholder="请输入密码" type="password" v-model="form.password"></el-input>
                        </el-form-item>
                    </template>

                    <template v-else-if="type == 0">
                        <el-form-item prop="telephone" label="手机号">
                            <el-input class="w-full" placeholder="请输入手机号" v-model="form.telephone"></el-input>
                        </el-form-item>
                        <el-form-item prop="msgcode" label="验证码">
                            <div class="flex">
                                <el-input placeholder="验证码" v-model="form.msgcode" class="mr-4 w-full"></el-input>
                                <el-button :type="stop ? 'info' : 'primary'" plain @click="getCode">{{ stop ? ('倒计时' + seconds + 's') : '获取验证码' }}</el-button>
                            </div>
                        </el-form-item>
                    </template>
                    
                    <template v-else-if="type == 2">
                        <div class="qrcode-box">
                            <img :src="qrcodeImg">
                        </div>
                    </template>

                    <el-form-item class="center pt-4" v-if="type != 2">
                        <el-button type="primary" @click="login" :loading="isBtnLoading">{{btnText}}</el-button>
                    </el-form-item>

                    <div v-if="type != 2" class="text-sm" style="margin-left: 80px">*如遗忘密码请使用app进行重置</div>
                    <el-row>
                        <el-col :span="12">
                            <div class="text-left mt-6 block text-sm">
                                <i  @click="toRegister" class="text-blue-light cursor-pointer">申请企业注册</i>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="text-right mt-6 block text-sm">
                                <i  @click="type = type == 2 ? 1 : 2" class="text-blue-light cursor-pointer">{{ type == 2  ? '验证码登录？' : '二维码登录？'}}</i>
                            </div>   
                        </el-col>
                    </el-row>
                    <!-- <el-row>
                        <el-col :span="24" >
                            <div class="text-center mt-6 block text-sm">
                                <i  @click="toRegister" class="text-blue-light cursor-pointer">申请企业注册</i>
                            </div>
                        </el-col>
                    </el-row> -->
                    

                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script>
    import {Input, Switch, Form, FormItem , Row , Col } from 'element-ui';
    import QRCode from 'qrcode'
    export default {
        components: {
            ElInput: Input,
            ElSwitch: Switch,
            ElForm: Form,
            ElFormItem: FormItem,
            ElRow: Row,
            ElCol: Col
        },
        props: [],
        data() {
            return {
                form: null,
                rules: {
                    username: [
                        {pattern: /^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$/, message: '请输入正确手机号码', trigger: 'blur'},
                        {required: true, message: '请输入手机号码', trigger: 'change'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    telephone: [
                        {required: true, message: '请输入手机号码', trigger: 'change'},
                        {pattern: /^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$/, message: '请输入正确手机号码', trigger: 'change'}
                    ],
                    msgcode: [
                        {required: true, message: '请输入验证码', trigger: 'blur'}
                    ],
                },
                type: 2, // 1: 账号密码, 0: 手机号验证码
                isBtnLoading: false,
                seconds: 60,
                stop: false,
                sha256: require('js-sha256'),
                randomUid:'',  //随机uid,
                qrcodeImg:'',
                timeOut:null
            };
        },
        computed: {
            btnText() {
                if (this.isBtnLoading) return '登录中...';
                return '登录';
            }
        },
        watch: {
            type(curVal) {
                this.createForm();
                if(curVal == 2){
                    this.makeQecode()
                }else{
                    clearTimeout(this.timeOut)
                }
            }
        },
        methods: {
            toRegister(){
                this.$router.push('/register');
            },
            makeQecode(){
                this.randomUid = this.randomString(false,19);
                let _url = 'bondme.net/api/user/qrcode/app/login?uid='+this.randomUid;
                this.createQrcode(_url);
            },
            getToken(){
                let _params = {
                    uid:this.randomUid
                }
                API.get('user/qrcode',{  
                        params : { 
                            uid:this.randomUid
                        }
                    }).then(response => {
                    console.log(response)
                    if(!response || Object.keys(response).length == 0){
                        this.timeOut = setTimeout(()=>{
                            this.getToken()
                        },3000)                        
                    }else{
                        SessionStore.set('loginMesg', response, response.expireAt);
                        this.fetchUser(response.expireAt);
                    }
                    
                });
            },
            createQrcode(_url){
                let _option = {
                    width:200,
                    height:200
                }
                QRCode.toDataURL(_url,_option)
                .then(url => {
                    console.log(url)
                    this.qrcodeImg = url
                    this.getToken()
                })
                .catch(err => {
                    console.error(err)
                })
            },
            randomString(randomTag,min,max){
                let str = "",
                    range = min,
                    arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
                    // 随机产生
                    if(randomTag){
                        range = Math.round(Math.random() * (max-min)) + min;
                    }
                    for(var i=0; i<range; i++){
                        let pos = Math.round(Math.random() * (arr.length-1));
                        str += arr[pos];
                    }
                    return str
            },
            login() {
                this.$refs.form.validate((valid) => {
                    if (!valid) return;
                    this.isBtnLoading = true;

                    let url = this.type ? 'users/login' : 'users/msglogin';
                    API.post(url, this.form).then((res) => {
                        console.log(res)
                        SessionStore.set('loginMesg', res, res.expireAt);
                        this.fetchUser(res.expireAt);
                    }).finally(() => this.isBtnLoading = false);
                });
            },
            // 获取用户信息，并跳转
            fetchUser(expire) {
                // get user info
                API.get('users/profile').then(response => {
                    SessionStore.set('userMesg', response.user, expire);
                    this.$router.push('/');
                }).finally(() => this.isBtnLoading = false);
            },
            createForm() {
                this.form = {
                    telephone: '',
                    msgcode: '',
                    username: '',
                    password: ''
                };
            },
            getCode() {
                if (this.stop) return Ele.$message.error('请等待' + this.seconds + '秒后, 重新发送');

                let data = {
                    ncode: '+86',
                    random: parseInt(Math.random() * 1000000),
                    telephone: this.form.telephone,
                    time: new Date().getTime(),
                };
                const shaCode = 'appkey=bondmeApiMsgSecretKey&random='+ data.random
                    + '&time=' + data.time
                    + '&mobile=' + data.telephone;

                data.sig = this.sha256(shaCode);

                API.post('msg', data).then(() => {
                    Ele.$message.success('发送成功');
                    this.stop = true;

                    let interval = setInterval(() => {
                        if (--this.seconds < 0) {
                            clearInterval(interval);
                            this.stop = false;
                            this.seconds = 60;
                        }
                    }, 1000);
                });
            }
        },
        created() {
            this.createForm();
            this.makeQecode();
        },
    };
</script>

<style lang="scss">
    .login-page {
        position: absolute;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        // background: #fff url('http://or9v0p9za.bkt.clouddn.com/downloadPc.png') center/cover no-repeat;

        .el-card{
            width: 100%;
            max-width: 400px;
        }

        .title {
            color: #20a0ff;
            font-weight: bold;
            font-size: 30px;
            text-align: center;
            line-height: 2.2;
            font-family: sans-serif;
        }

        .el-button{
            width: 100%;
        }

        .qrcode-box{
            width: 200px;
            height: 200px;
            margin: 0 auto;
        }
    }
</style>
